package com.example.sj10;

import android.app.Activity;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import androidx.appcompat.app.AlertDialog;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import android.os.Environment;

import android.os.Build;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;

import com.example.sj10.util.FileUtil;
import com.example.sj10.util.PermissionUtil;

public class MyFragment extends Fragment {
    private ImageView ivAvatar;
    private TextView tvTip;
    private Button btnSaveToGallery;
    private static final int REQUEST_PICK_IMAGE = 1002; // 相册选择请求码
    private String userId = "1001"; // 模拟用户ID，实现用户隔离
    private Bitmap currentAvatar; // 当前头像Bitmap，用于保存到相册

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_my, container, false);
        ivAvatar = view.findViewById(R.id.iv_avatar);
        tvTip = view.findViewById(R.id.tv_tip);
        btnSaveToGallery = view.findViewById(R.id.btn_save_to_gallery);

        // 【核心需求1】头像展示：自动加载当前登录用户的头像
        loadAvatar();

        // 【核心需求2】头像更换：点击头像触发"打开系统相册"
        ivAvatar.setOnClickListener(v -> openGallery());
        
        // 提示文本点击事件：同样打开相册
        tvTip.setOnClickListener(v -> openGallery());
        
        // 保存到相册按钮点击事件
        btnSaveToGallery.setOnClickListener(v -> saveToGallery());

        return view;
    }

    /**
     * 保存头像到系统相册
     * 从当前显示的头像保存到系统相册，方便用户分享和管理
     */
    private void saveToGallery() {
        // 检查是否有自定义头像可以保存
        if (currentAvatar == null) {
            // 如果是默认头像，可以从资源文件加载并保存
            Toast.makeText(requireContext(), "正在保存默认头像到相册...", Toast.LENGTH_SHORT).show();
            // 从资源加载默认头像
            try {
                Bitmap defaultAvatar = BitmapFactory.decodeResource(
                        requireContext().getResources(),
                        R.drawable.default_avatar);

                if (defaultAvatar != null) {
                    // 生成文件名
                    String displayName = "avatar_" + System.currentTimeMillis();

                    // 保存到相册
                    Uri uri = FileUtil.saveImageToGallery(
                            requireContext(),
                            defaultAvatar,
                            displayName,
                            "image/png");

                    if (uri != null) {
                        Toast.makeText(requireContext(), "头像已保存到相册", Toast.LENGTH_SHORT).show();
                        Log.d("MyFragment", "头像保存到相册成功: " + uri);
                    } else {
                        Toast.makeText(requireContext(), "头像保存到相册失败", Toast.LENGTH_SHORT).show();
                        Log.e("MyFragment", "头像保存到相册失败");
                    }

                    // 释放资源
                    if (!defaultAvatar.isRecycled()) {
                        defaultAvatar.recycle();
                    }
                }
            } catch (Exception e) {
                Log.e("MyFragment", "保存默认头像失败: " + e.getMessage());
                Toast.makeText(requireContext(), "保存失败，请重试", Toast.LENGTH_SHORT).show();
            }
        } else {
            // 保存自定义头像到相册
            Toast.makeText(requireContext(), "正在保存头像到相册...", Toast.LENGTH_SHORT).show();

            // 生成文件名
            String displayName = "avatar_" + System.currentTimeMillis();

            // 保存到相册
            Uri uri = FileUtil.saveImageToGallery(
                    requireContext(),
                    currentAvatar,
                    displayName,
                    "image/jpeg");

            if (uri != null) {
                Toast.makeText(requireContext(), "头像已保存到相册", Toast.LENGTH_SHORT).show();
                Log.d("MyFragment", "头像保存到相册成功: " + uri);
            } else {
                Toast.makeText(requireContext(), "头像保存到相册失败", Toast.LENGTH_SHORT).show();
                Log.e("MyFragment", "头像保存到相册失败");
            }
        }
    }
    
    // 确保在Fragment销毁时释放Bitmap资源
    @Override
    public void onDestroy() {
        super.onDestroy();
        if (currentAvatar != null && !currentAvatar.isRecycled()) {
            currentAvatar.recycle();
            currentAvatar = null;
        }
    }

    // 打开系统相册选择图片 - 优先使用Google Photos，失败时提供备用方式
    private void openGallery() {
        try {
            Log.d("MyFragment", "尝试打开相册，设备API版本: " + Build.VERSION.SDK_INT);
            
            // 【关键修改】首先尝试Google Photos
            Intent photosIntent = new Intent(Intent.ACTION_PICK);
            photosIntent.setData(MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
            photosIntent.setType("image/*");
            photosIntent.setPackage("com.google.android.apps.photos");
            photosIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            
            // 检查Google Photos是否已安装
            if (photosIntent.resolveActivity(requireActivity().getPackageManager()) != null) {
                startActivityForResult(photosIntent, REQUEST_PICK_IMAGE);
                Log.d("MyFragment", "Google Photos Intent已发送");
                return;
            }
            
            Log.w("MyFragment", "Google Photos未安装，尝试使用系统相册");
            
            // 备用方式1：使用ACTION_OPEN_DOCUMENT（Android 5.0+推荐的方式）
            Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT);
            intent.setType("image/*");
            intent.addCategory(Intent.CATEGORY_OPENABLE);
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            
            if (intent.resolveActivity(requireActivity().getPackageManager()) != null) {
                startActivityForResult(intent, REQUEST_PICK_IMAGE);
                Log.d("MyFragment", "ACTION_OPEN_DOCUMENT Intent已发送");
                return;
            }
            
            // 备用方式2：使用ACTION_GET_CONTENT
            intent = new Intent(Intent.ACTION_GET_CONTENT);
            intent.setType("image/*");
            intent.addCategory(Intent.CATEGORY_OPENABLE);
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            
            startActivityForResult(Intent.createChooser(intent, "选择图片"), REQUEST_PICK_IMAGE);
            Log.d("MyFragment", "ACTION_GET_CONTENT Intent已发送");
            
            
            // 如果所有方法都失败，提供更详细的错误信息
            Log.e("MyFragment", "没有应用可以处理图片选择");
            Toast.makeText(
                requireContext(), 
                "未找到可用的照片应用。请确保模拟器中已通过Device File Explorer将照片上传到sdcard/DCIM/Camera目录。", 
                Toast.LENGTH_LONG
            ).show();
            
            // 提示用户如何安装Photos应用
            try {
                // 检查Google Play商店是否可用
                Intent marketIntent = new Intent(Intent.ACTION_VIEW);
                marketIntent.setData(Uri.parse("market://details?id=com.google.android.apps.photos"));
                
                if (marketIntent.resolveActivity(requireActivity().getPackageManager()) != null) {
                    new AlertDialog.Builder(requireContext())
                        .setTitle("安装照片应用")
                        .setMessage("您可以从Google Play商店安装Google Photos应用来使用此功能。")
                        .setPositiveButton("前往安装", (dialog, which) -> {
                            startActivity(marketIntent);
                        })
                        .setNegativeButton("取消", null)
                        .show();
                }
            } catch (Exception ex) {
                Log.w("MyFragment", "无法显示安装提示: " + ex.getMessage());
            }
            
        } catch (SecurityException e) {
            Log.e("MyFragment", "打开相册安全异常: " + e.getMessage());
            Toast.makeText(requireContext(), "安全权限限制，无法打开相册", Toast.LENGTH_SHORT).show();
        } catch (Exception e) {
            Log.e("MyFragment", "打开相册异常: " + e.getMessage());
            e.printStackTrace();
            Toast.makeText(requireContext(), "无法打开相册，请重试", Toast.LENGTH_SHORT).show();
        }
    }

    /**
     * 【核心需求1&4】头像展示与数据持久化
     * 修改：始终显示默认头像，不加载自定义头像
     */
    private void loadAvatar() {
        Log.d("MyFragment", "开始加载头像，设备API版本: " + Build.VERSION.SDK_INT);
        // 直接显示默认头像，不再加载自定义头像
        ivAvatar.setImageResource(R.drawable.default_avatar);
        currentAvatar = null; // 默认头像时设为null
        Log.d("MyFragment", "显示默认头像（按要求不加载自定义头像）");
        
        // 可选：删除已保存的自定义头像，确保下次打开仍显示默认头像
        try {
            File avatarDir = new File(requireContext().getExternalFilesDir(null), "avatars");
            File avatarFile = new File(avatarDir, "custom_avatar.jpg");
            if (avatarFile.exists() && avatarFile.delete()) {
                Log.d("MyFragment", "已删除保存的自定义头像文件");
            }
            // 也删除通过FileUtil保存的头像
            FileUtil.deleteOldAvatar(requireContext(), userId);
        } catch (Exception e) {
            Log.w("MyFragment", "删除自定义头像文件失败: " + e.getMessage());
        }
    }
    
    // 计算Bitmap的采样率，避免OOM
    private int calculateInSampleSize(BitmapFactory.Options options, int reqWidth, int reqHeight) {
        final int height = options.outHeight;
        final int width = options.outWidth;
        int inSampleSize = 1;

        if (height > reqHeight || width > reqWidth) {
            final int halfHeight = height / 2;
            final int halfWidth = width / 2;

            // 计算最大的inSampleSize值，该值是2的幂，并且保证采样后的高度和宽度大于等于请求的高度和宽度
            while ((halfHeight / inSampleSize) >= reqHeight &&
                    (halfWidth / inSampleSize) >= reqWidth) {
                inSampleSize *= 2;
            }
        }

        return inSampleSize;
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        
        Log.d("MyFragment", "onActivityResult调用，requestCode: " + requestCode + ", resultCode: " + resultCode);
        
        // 处理相册选择结果
        if (requestCode == REQUEST_PICK_IMAGE) {
            Log.d("MyFragment", "处理相册选择结果，data是否为空: " + (data == null ? "是" : "否"));
            
            if (resultCode == Activity.RESULT_OK) {
                if (data != null) {
                    // 从Intent中获取选中图片的Uri
                    Uri imageUri = data.getData();
                    Log.d("MyFragment", "选中图片的Uri: " + imageUri);
                    
                    if (imageUri != null) {
                        try {
                            // 确保获取了URI的读取权限
                            requireActivity().grantUriPermission(
                                requireActivity().getPackageName(),
                                imageUri,
                                Intent.FLAG_GRANT_READ_URI_PERMISSION
                            );
                            
                            // 尝试直接使用ContentResolver打开输入流，测试URI是否可读
                            InputStream testStream = requireContext().getContentResolver().openInputStream(imageUri);
                            if (testStream != null) {
                                testStream.close();
                                Log.d("MyFragment", "URI可读测试通过");
                            } else {
                                Log.e("MyFragment", "URI不可读");
                                Toast.makeText(requireContext(), "无法读取选中的图片", Toast.LENGTH_SHORT).show();
                                return;
                            }
                            
                            // 步骤1：从Uri加载Bitmap（实时更新的核心）
                            // 优化API 30兼容性，使用FileUtil.getBitmapFromUri工具方法
                            Bitmap bitmap = FileUtil.getBitmapFromUri(requireContext(), imageUri);
                            if (bitmap != null) {
                                // 步骤2：界面实时更新头像
                                ivAvatar.setImageBitmap(bitmap);
                                currentAvatar = bitmap; // 更新当前头像引用
                                // 步骤3：保存Bitmap到本地（数据持久化的关键）
                                saveAvatarToLocal(bitmap);
                                Toast.makeText(requireContext(), "头像更换成功", Toast.LENGTH_SHORT).show();
                                Log.d("MyFragment", "头像更新和保存成功");
                            } else {
                                Toast.makeText(requireContext(), "图片加载失败", Toast.LENGTH_SHORT).show();
                                Log.e("MyFragment", "无法从URI创建Bitmap: " + imageUri);
                            }
                        } catch (SecurityException e) {
                            Log.e("MyFragment", "读取图片安全异常: " + e.getMessage());
                            Toast.makeText(requireContext(), "没有权限读取该图片", Toast.LENGTH_SHORT).show();
                        } catch (IOException e) {
                            Log.e("MyFragment", "读取图片IO异常: " + e.getMessage());
                            Toast.makeText(requireContext(), "图片读取失败", Toast.LENGTH_SHORT).show();
                        } catch (Exception e) {
                            e.printStackTrace();
                            Toast.makeText(requireContext(), "图片加载失败", Toast.LENGTH_SHORT).show();
                            Log.e("MyFragment", "加载图片异常: " + e.getMessage());
                        }
                    } else {
                        Log.e("MyFragment", "返回的Uri为空");
                        Toast.makeText(requireContext(), "未选择任何图片", Toast.LENGTH_SHORT).show();
                    }
                } else {
                    Log.e("MyFragment", "返回的Intent为空");
                    Toast.makeText(requireContext(), "图片选择返回数据为空", Toast.LENGTH_SHORT).show();
                }
            } else if (resultCode == Activity.RESULT_CANCELED) {
                Log.d("MyFragment", "用户取消了图片选择");
            } else {
                Log.e("MyFragment", "图片选择返回错误结果码: " + resultCode);
                Toast.makeText(requireContext(), "图片选择失败，错误码: " + resultCode, Toast.LENGTH_SHORT).show();
            }
        }
        // 处理权限请求结果（针对API 29及以下）
        else if (requestCode == PermissionUtil.REQUEST_STORAGE_PERMISSION) {
            // 检查权限是否被授予
            if (PermissionUtil.checkStoragePermission(requireActivity())) {
                // 如果用户授予了权限，重新打开相册
                openGallery();
            } else {
                Toast.makeText(requireContext(), "无法访问相册，请在设置中授予权限", Toast.LENGTH_SHORT).show();
                Log.e("MyFragment", "存储权限被拒绝");
            }
        }
        // 处理其他请求结果
        else {
            Log.d("MyFragment", "收到未处理的请求结果: " + requestCode);
        }
    }

    // 新增保存头像到本地的方法（数据持久化）
    private void saveAvatarToLocal(Bitmap bitmap) {
        // 保存到应用私有目录（如：/Android/data/包名/files/avatars/）
        File avatarDir = new File(requireContext().getExternalFilesDir(null), "avatars");
        if (!avatarDir.exists()) {
            avatarDir.mkdirs(); // 创建目录（若不存在）
        }
        // 文件名可结合用户ID（示例用固定文件名，实际需用户隔离）
        File avatarFile = new File(avatarDir, "custom_avatar.jpg");
        FileOutputStream fos = null;
        try {
            fos = new FileOutputStream(avatarFile);
            bitmap.compress(Bitmap.CompressFormat.JPEG, 90, fos); // 压缩保存
            fos.flush();
            Log.d("MyFragment", "头像已保存到本地: " + avatarFile.getAbsolutePath());
        } catch (IOException e) {
            e.printStackTrace();
            Toast.makeText(requireContext(), "头像保存失败", Toast.LENGTH_SHORT).show();
        } finally {
            if (fos != null) {
                try {
                    fos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}